<?php

namespace App\HttpController\Api\Admin;

use App\HttpController\Api\ApiBase;
use App\HttpController\ResponseCode;
use App\Service\BaseService;
use EasySwoole\Component\Context\ContextManager;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\DbManager;
use EasySwoole\Validate\Validate;

// 后台管理基础控制器定义

/**
 * @property BaseService $service
 */
class AdminBase extends ApiBase
{
    //public才会根据协程清除
    public $who;

    protected $service;

    //白名单
    protected $whiteList = [];

    /**
     * onRequest
     * @param null|string $action
     * @return bool|null
     * @throws \Throwable
     * @author LZH
     */
    public function onRequest(?string $action): ?bool
    {
        if (parent::onRequest($action)) {
            //白名单判断，即不需要登录就可访问
            if (in_array($action, $this->whiteList)) {
                return true;
            }
            //获取登入信息
            if (!$this->getWho()) {
                $this->fail(ResponseCode::CODE_UNAUTHORIZED);
                return false;
            }
            return true;
        }
        return false;
    }

    /**
     * getWho
     * @return array
     * @author LZH
     */
    public function getWho()
    {
        if (!empty($this->who)) {
            return $this->who;
        }

        $token = $this->request()->getHeader("authorization")[0];
        if ($token && strpos($token, 'Bearer ') !== false) {
            $token = str_replace("Bearer ", null, $token);
            // JWT解密token
            $userId = parse_token($token);

            // 这里需要绕过模型get/all查询方法，因为这两个方法会自动添加school_code字段，但登陆的时候是不知道这个字段的
            $builder = new QueryBuilder();
            $builder->setPrefix(DB_PREFIX)->where('id', $userId)->getOne('admin');
            $ret = DbManager::getInstance()->query($builder, false);
            $userInfo = $ret->getResultOne();

            $this->who = $userInfo; // 数组结果
            ContextManager::getInstance()->set('user', $this->who);
            return $this->who;
        }
        return null;
    }

    protected function getValidateRule(?string $action): ?Validate
    {
        return null;
        // https://cloud.tencent.com/developer/article/1556450
        // TODO: Implement getValidateRule() method.
    }

    /**
     * 获取数据列表，GET
     */
    public function list()
    {
        return $this->respondQuery($this->service->getList());
    }

    /**
     * 获取数据详情，GET
     */
    public function info()
    {
        $result = $this->service->info();
        if (!empty($result)) {
            return $this->respondQuery($result);
        } else {
            return $this->failServerError();
        }
    }

    /**
     * 添加或编辑，POST/PUT
     */
    public function edit()
    {
        $result = $this->service->edit();
        $this->log_info('添加或编辑结果：'.$result);
        if ($result) {
            return $this->respondCreated($result);
        } else {
            return $this->failServerError();
        }
    }

    /**
     * 删除数据，DELETE
     */
    public function destroy()
    {
        if ($this->service->destroy()) {
            return $this->respondDeleted();
        } else {
            return $this->failServerError();
        }
    }

    /**
     * 设置状态，PATCH
     */
    public function status()
    {
        if ($this->service->status()) {
            return $this->respondNoContent();
        } else {
            return $this->failServerError();
        }
    }

    /**
     * 获取所有的id和名称对，GET
     */
    public function getIdName()
    {
        $result = $this->service->getIdName();
        if (!empty($result)) {
            return $this->respondQuery($result);
        } else {
            return $this->failServerError();
        }
    }

}
